package edu.friday.repository.custom.impl;

import edu.friday.model.SysMenu;
import edu.friday.repository.custom.SysMenuCustomRepository;
import edu.friday.utils.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

public class SysMenuCustomRepositoryImpl implements SysMenuCustomRepository {
    public static String SELECT = " select distinct m.* from sys_menu m ";
    public static String JOIN_ROLE_MENU = " left join sys_role_menu rm on m.menu_id = rm.menu_id ";
    public static String JOIN_USER_ROLE = " left join sys_user_role ur on rm.role_id = ur.role_id ";
    public static String JOIN_ROLE = " left join sys_role ro on ur.role_id = ro.role_id ";
    public static String ORDER_BY = " order by parent_id, order_num ";

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<SysMenu> selectMenuListByUserId(SysMenu sysMenu, Long userId) {
        boolean queryMenuName = null != sysMenu && !StringUtils.isBlank(sysMenu.getMenuName());
        boolean queryVisible = null != sysMenu && !StringUtils.isBlank(sysMenu.getVisible());

        StringBuffer sql = new StringBuffer();

        sql.append(SELECT);
        sql.append(JOIN_ROLE_MENU);
        sql.append(JOIN_USER_ROLE);
        sql.append(" where ur.user_id = :userId ");
        if (queryMenuName){
            sql.append(" AND menu_name like concat('%',:menuName, '%') ");
        }
        sql.append(ORDER_BY);

        Query query = entityManager.createNativeQuery(sql.toString(),SysMenu.class).setParameter("userId",userId);
        if (queryMenuName){
            query.setParameter("menuName",sysMenu.getMenuName());
        }
        if (queryVisible){
            query.setParameter("visible",sysMenu.getVisible());
        }
        return query.getResultList();
    }
}
